package com.personal.sfe.auth;

import com.personal.sfe.common.Result;
import com.personal.sfe.security.CustomUserDetails;
import com.personal.sfe.token.TokenService;
import com.personal.sfe.user.bo.UserBO;
import com.personal.sfe.user.bo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * @author: 梁奔
 * @date: 2025/11/04
 */

@RestController
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenService tokenService;

    @PostMapping("/api/auth/login")
    public Result login(@RequestBody LoginRequest request) {
        try {
            //创建未认证的token
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword());
            //进行认证
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            //认证成功，生成token
            String token = tokenService.generateToken(request.getUsername());
            return Result.ok("token", token);
        } catch (Exception e) {
            //认证失败
            return Result.err("用户名或密码错误");
        }
    }

    @PostMapping("/api/auth/logout")
    public Result logout(@RequestHeader("Authorization") String authHeader) {
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            tokenService.invalidateToken(token);
        }
        return Result.ok("登出成功");
    }

    @GetMapping("/api/auth/me")
    public Result me() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        CustomUserDetails details = (CustomUserDetails) authentication.getPrincipal();
        UserBO userBO = details.getUserBO();
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userBO, userVO);
        return Result.ok(userVO);
    }
}
